const app = getApp();
import { releaseDynamics, scenicspotList } from "../../../api/release"
import { selectAllLabel } from "../../../api/homePage";
import { getAddress, getLnglat, getlatlngAddress, getKeyAddress } from "../../../utils/address"
import { getStorage } from "../../../utils/localStorage"
Page({
  data: {
    navData: {
      level: 2,
      title: "发布动态"
    },
    mapData: {
      scale: 16, //缩放级别，取值范围为3-20
      minScale: 3, //最小缩放级别
      maxScale: 20, //最大缩放级别
      enable3D: true, //展示3D楼块
      enableZoom: true, //是否支持缩放
      enableScroll: true, //是否支持拖动
      enableBuilding: true, //是否展示建筑物
      tapFlag: false, //是否支持点击地图打开第三方地图功能
    },
    htIndex: null,
    latLng: null,
    fomr: null,
    labelList: [],
    sceniceList: [],
    sceniceNameList: [],
    sceniceIdList: [],
    landscapesName: "",
    labelData: [],
    navMargin: app.globalData.navHeight + app.globalData.navTop,
    adresList: [], //地址列表
    adresFlag: false, //地址列表状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (JSON.stringify(options) != "{}") {
      let item = JSON.parse(decodeURIComponent(options.item));
      //参与话题数据遍历
      let labelArr = item.labelName.split(","),
        arr = [];
      labelArr.forEach((item, index) => {
        arr.push({ labelName: item })
      });
      this.setData({
        labelData: arr,
        landscapesName: item.landscapesName,
        form: item,
        latLng: item.longitude + "," + item.latitude
      });
      console.log(this.data.form, 'update');
    };
    this.reset();
    this.getCurrentAddress();
    this.getScenicspotList();
  },
  onShow() {
    if (this.data.data && this.data.data.length != 0) {
      let arr = this.data.data, //选择的标签数组
        idArr = [];

      arr.forEach(item => {
        idArr.push(item.id);
      });

      this.setData({
        labelData: arr,
        "form.labelId": arr.join(","),
      });
    };
  },

  /* 表单字段重置 */
  reset() {
    this.setData({
      form: {
        userId: getStorage('user').id,
        image: null,
        title: null,
        textContent: null,
        latitude: null,
        longitude: null,
        locationName: null,
        landscapesId: null,
        labelId: null
      }
    });
  },

  /* 获取当前用户位置信息 */
  getCurrentAddress() {
    getAddress().then(res => {
      const { address, location } = res.result;
      this.setData({
        "form.locationName": address,
        latLng: location.lng + "," + location.lat,
        "form.longitude": location.lng,
        "form.latitude": location.lat,
      });
    })
  },

  //获取景区列表
  async getScenicspotList() {
    let res = await scenicspotList();
    let { code, data } = res.data;
    let arrName = [], arrId = [];
    if (code === 200) {
      data.forEach(item => {
        arrName.push(item.landscapesName);
        arrId.push(item.id);
      });
      this.setData({
        sceniceNameList: arrName,
        sceniceIdList: arrId,
      });
    };
  },

  //获取上传图片路径
  uploadImg(e) {
    const images = e.detail.join(",");
    console.log(images, 'images');
    this.setData({
      "form.image": images
    });
  },

  //标题bindinput事件
  inputTitle(e) {
    const val = e.detail.value;
    this.setData({
      "form.title": val,
    });
  },

  //正文bindinput事件
  inputContent(e) {
    const val = e.detail.value;
    this.setData({
      "form.textContent": val,
    });
  },
  //参与话题事件
  async tction(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pagesShouYe/pages/bianji/index?type=' + '发布' + '&dynamicId=' + id,
    })
  },
  //添加地点
  bindAddress(e) {
    let value = e.detail.value;
    if (value) {
      getKeyAddress(value).then(res => {
        this.setData({
          adresList: res,
          adresFlag: true,
        });
      });
    } else {
      this.setData({
        adresFlag: false,
      });
    };
  },
  //地址列表点击事件
  xzAddress(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      "form.locationName": item.title,
      "form.latitude": item.location.lat,
      "form.longitude": item.location.lng,
      latLng: item.location.lng + ',' + item.location.lat,
      adresFlag: false,
    });
  },
  //全局点击事件
  allTap() {
    this.setData({
      adresFlag: false,
      "form.locationName": "",
    });
  },
  //发布乡音
  async submit() {
    const _this = this.data;
    console.log(this.data.form, 'form');
    if (!_this.form.image) {
      this.messagefunc("请上传图片");
    } else if (!_this.form.title) {
      this.messagefunc("请填写标题");
    } else if (!_this.form.textContent) {
      this.messagefunc("请添加正文");
    } else if (!_this.form.labelId) {
      this.messagefunc("请选择话题");
    } else if (!_this.form.locationName) {
      this.messagefunc("请选择发布地址");
    } else {
      let res = await releaseDynamics(_this.form);
      const { code, msg } = res.data;
      if (code === 200) {
        wx.showToast({
          icon: "none",
          title: "发布成功",
        });
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/index/index?index=' + 5,
          });
        }, 1000)
      }
    }
  },

  //消息提示公用方法
  messagefunc(title) {
    wx.showToast({
      icon: 'none',
      title: title,
      duration: 2000,
      mask: true
    });
  },
  //头部返回事件
  back() {
    let pages = getCurrentPages(); // 获取页面栈
    // let currPage = pages[pages.length - 1]; // 当前页面
    let prevPage = pages[pages.length - 2]; // 上一个页面
    prevPage.setData({
      footerIndex: getStorage('pageIndex'),
    });
    wx.navigateBack({
      delta: 1
    })
  },
  //地图点击事件
  async mapTap(e) {
    let item = e.detail;
    this.setData({
      latLng: item.longitude + "," + item.latitude,
      "form.locationName": item.address,
      "form.latitude": item.latitude,
      "form.longitude": item.longitude,
    });
  },
  //地图上重置按钮点击事件
  czAddressTap() {
    // this.setData({
    //   latLng: getStorage("latLng").lng + "," + getStorage("latLng").lat
    // });
    this.getCurrentAddress();
  },
  //所属景区change事件
  bindPickerChange(e) {
    let index = Number(e.detail.value);
    let id = this.data.sceniceIdList[index];
    let name = this.data.sceniceNameList[index];
    this.setData({
      "form.landscapesId": id,
      landscapesName: name
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})